<template>
  <div id="cesiumContainer"></div>
  <div id="showBtn">
    <button @click="changeEntityShow">显示管线</button>
  </div>
</template>
<script setup>
import * as Cesium from 'cesium'
import Viewer from 'cesium/Source/Widgets/Viewer/Viewer';
import * as turf from '@turf/projection'
import coordtransform from 'coordtransform'
import { onMounted  } from 'vue';
import geojson from '../public/geojson/LineString_pipe.json'
let viewer = null;


// const computeCircle = (radius) => {
//   const positions = [];
//   for (let i = 0; i < 360; i++) {
//       const radians = Cesium.Math.toRadians(i);
//       positions.push(
//       new Cesium.Cartesian2(
//           radius * Math.cos(radians),
//           radius * Math.sin(radians)
//       )
//       );
//   }
//   return positions;
// };

const download = (filename, text) => {
  let pom = document.createElement( 'a');
  pom.setAttribute('href','data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  pom.setAttribute('download',filename);
  if (document.createEvent) {
    var event = document .createEvent( 'MouseEvents');
    event.initEvent('click',true,true);
    pom.dispatchEvent(event);
  }else{
    pom.click();
  } 
}
const initMap = async () => {
  Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5Yjc0MTYzMS1mMmZmLTRiNTctODZhMi1mZjRjYzQ2NTFmMWEiLCJpZCI6MTMyNDAyLCJpYXQiOjE2ODA3NjYzMDF9.9Jj665lzy-TlV5dJkSBZKBmHnSaqyOVrRM5cvI_t8rg";
  
  const esri = new Cesium.ArcGisMapServerImageryProvider({
    enablePickFeatures: false,
    url: "https://services.arcgisonline.com/ArcGIS/rest/services/world_Imagery/MapServer"
  });
  viewer = new Cesium.Viewer("cesiumContainer",{
    // infoBox:false,
    terrainProvider:Cesium.createWorldTerrain({
      requestWaterMask:true ,//添加水面特效
      // requestVertexNormals:true
    }),
    // imageryProvider:esri
    // imageryProvider:new Cesium.UrlTemplateImageryProvider({
    //   url:'http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
    //   minimumLevel:1,
    //   maximumLevel:18
    // })
  });

//1.Cesium加载高德矢量地图(GCJ02)
var layer = new Cesium.UrlTemplateImageryProvider({
            url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
            minimumLevel: 4,
            maximumLevel: 18
        })
        viewer.imageryLayers.addImageryProvider(layer);

//2.Cesium加载高德影像
        var imgLayer = new Cesium.UrlTemplateImageryProvider({
            url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
            minimumLevel: 3,
            maximumLevel: 18
        })
        viewer.imageryLayers.addImageryProvider(imgLayer);

//3.Cesium加载注记要素
        var annLayer = new Cesium.UrlTemplateImageryProvider({
            url: "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
            minimumLevel: 3,
            maximumLevel: 18
        })
        viewer.imageryLayers.addImageryProvider(annLayer);


  //添加百度地图
  // const baiduMap = new Cesium.BingMapsImageryProvider({
  //   url:'https://api.map.baidu.com/api?v=3.0&ak=2ZPtEQ1boGQEZYUkECaD1T6Ttdcyqj01'
  // })
  // debugger
  // // viewer.imageryLayers.addImageryProvider(baiduMap);
  // const imageryLayer = new Cesium.ImageryLayer(baiduMap);
  // viewer.imageryLayers.add(imageryLayer);

  // //添加自己部署的WMS图层
  const provider = new Cesium.WebMapServiceImageryProvider({
    url:'/geoserver/aql_home/wms?',
    layers:'aql_home:LineString_pipeline',
    crs:'WGS84',
    parameters:{
      transparent:true,
      format:'image/png'
    },
    //超出这个区域就不加载地图数据
    // rectangle:new Cesium.Rectangle(Cesium.Math.toRadians(105.01963613519874),Cesium.Math.toRadians(28.706653644870876),Cesium.Math.toRadians(105.15769502125254),Cesium.Math.toRadians(28.76093215563257))
  });
  // const imageryLayer = new Cesium.ImageryLayer(provider);
  // viewer.imageryLayers.add(imageryLayer);


//   const esri = await Cesium.ArcGisMapServerImageryProvider.fromUrl(
//     "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
// );
//   const index = 0
//   viewer.imageryLayers.add(esri,index) 

  // 创建一个地形提供器对象
// var terrainProvider = new Cesium.CesiumTerrainProvider({
//     url : 'http://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer',
// });

// viewer.terrainProvider = terrainProvider;

  //经纬度转笛卡尔坐标
  const position  = new Cesium.Cartesian3.fromDegrees(105.06946143839523, 28.72599712032565, 1000);//经纬度转成笛卡尔坐标：(经度、纬度、离地高度) --->笛卡尔坐标：(横(X)、纵(y)、离地的高度(z)) 
  //2.3 lookAt 锁住视角，只能定焦到一个点
  viewer.camera.lookAt(position,
    new Cesium.HeadingPitchRange(
      Cesium.Math.toRadians(0),
      Cesium.Math.toRadians(-90),
      2000
    ))

    //添加一个标牌
  //  const dataSource = viewer.dataSources = new Cesium.CustomDataSource('entitiesDataSource');
    const billbord1 = viewer.entities.add({
      position:new Cesium.Cartesian3.fromDegrees(105.06946143839523, 28.72599712032565,500),
      billboard:{
        image:'/image/biaoji.png',
        scale:0.6,
       // sizeInMeters:true,//大小是否以米为单位，就会近大远小，一般情况下不用
        heightReference : Cesium.HeightReference.NONE,
        horizontalOrigin : Cesium.HorizontalOrigin.CENTER,//水平方向
        verticalOrigin : Cesium.VerticalOrigin.BOTTOM,//垂直方向
      },
      label:{
        text:'标记',
        fillColor:Cesium.Color.RED
      },
      point:{
        pixelSize:10,
        color:Cesium.Color.RED
      }
    })
    //引入高德地图地图，因为高德地图是GCJ02,所以需要把WGS84坐标系的数据转一下
    // geojson.features.forEach(item => {
    //   const p1 = coordtransform.wgs84togcj02(item.geometry.coordinates[0][0],item.geometry.coordinates[0][1]);
    //   const p2 = coordtransform.wgs84togcj02(item.geometry.coordinates[1][0],item.geometry.coordinates[1][1]);
    //   item.geometry.coordinates = [p1,p2];
    // })
    // // debugger
    // download('newGeoJson',JSON.stringify(geojson));
    // 添加geijson
    // Cesium.GeoJsonDataSource.load(converted).then(res =>{
    Cesium.GeoJsonDataSource.load('../public/geojson/11.json').then(res =>{
        viewer.dataSources.add(res);
        res.entities.values.forEach(entity => {
          entity.polyline.material = Cesium.Color.RED;
          entity.polyline.width = 4;
          // entity.polylineVolume.shape = computeCircle(2.0);
          // entity.polylineVolume.cornerType = Cesium.CornerType.ROUND;
        })
    })

    new Cesium.Cesium3DTitle

    //添加鼠标事件
    /**
     * 1、添加事件
     * 2、获取事件点 viewer.camera.getPicker()
     * 2、判断事件picker是否在地球上：Cesium.defined(position)
     * 3、
     */
     viewer.scene.globe.depthTestAgainstTerrain = true;
     /**
      * 添加等高线
      */
     const elevationConterMaterial = new Cesium.Material({
      fabric:{
        type:'ElevationContour',
        uniforms:{
          color:new Cesium.Color(1.0,0.0,0.0,1.0),
          spacing:10,
          width:2
        }
      }
     })
    //  viewer.scene.globe.material = elevationConterMaterial;

     /**
      * 添加地形渲染
      */
    //  const elevationRampMaterial = new Cesium.Material({
    //   fabric:{
    //     type:'ElevationRamp',
    //     uniforms:{
    //       image:'./assets/11.png',
    //       minimumHeight:10,
    //       maximumHeight:500
    //     }
    //   }
    //  })
    //  viewer.scene.globe.material = elevationRampMaterial;

    const elevationBandMaterial = new Cesium.createElevationBandMaterial({
      scene :  viewer.scene,
      layers : [{
          entries : [{
              height : 400.0,
              color : new Cesium.Color(0.0, 0.0, 0.0, 1.0)
          }, {
              height : 848.0,
              color : new Cesium.Color(1.0, 1.0, 1.0, 1.0)
          }],
          extendDownwards : true,
          extendUpwards : true,
      }, {
          entries : [{
              height : 700.0,
              color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
          }, {
              height : 710.0,
              color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
          }]
      }]
    });
  // viewer.scene.globe.material = elevationBandMaterial;

}

const changeEntityShow = ()=>{
  debugger
  // viewer.dataSources._dataSources[0]._entityCollection._entities._array[0]
  viewer.dataSources._dataSources[0]._entityCollection._entities._array.forEach(entity => {
    debugger
          entity.polyline.material = Cesium.Color.RED;
          entity.polyline.width = 4;
          debugger
          // entity.isShowing = true;
          // entity.polylineVolume.shape = computeCircle(2.0);
          // entity.polylineVolume.cornerType = Cesium.CornerType.ROUND;
        })
}
onMounted( () => {
  initMap();
  console.log(turf)

  
})
</script>
<style scoped lang="scss">
#app{
  width:100vw;
  /* height: 100vh; */
}
#cecsium{
  width: 100vw;
  height: 200vh;
}

:deep(){
  // 隐藏左下角的Cesium logo
  .cesium-viewer .cesium-viewer-bottom{
    display: none;
  }
}
#showBtn{
  width: 100px;
  height: 40px;
  position: absolute;
  top: 10px;
  left: 100px;
  background-color: rgba(1,0,0,1);
  color: #fff;
}
</style>
